package cn.itcast.mq.spring;

import cn.itcast.mq.config.CommonConfig;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.itcast.mq.config.CommonConfig.DIRECT_EXCHANGE;

/**
 *
 * @Author mr.wu
 * @Date 2025/1/11 10:23
 */
@SpringBootTest
@Slf4j
@RunWith(SpringRunner.class)
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Test
    public void sendMessage() throws InterruptedException {
        String message = "Hello rabbitmq ~";

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        //设置生产消息确认机制回调publish-confirm回调方法
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               if(ack){
                   log.info("消息发送成功,消息ID: {}", correlationData.getId());
               }else{
                   log.info("消息发送失败,消息ID: {},原因: {}", correlationData.getId(), cause);
               }
           }
       });

       //设置生产者消息确认机制publish-return回调方法
       rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
           @Override
           public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
               log.info("消息发送到队列失败，消息：{}，应答码：{}，原因：{}，交换机：{}，路由KEY：{}",message, replyCode, replyText, exchange, routingKey);
           }
       });


       rabbitTemplate.convertAndSend ( DIRECT_EXCHANGE , CommonConfig.DIRECT_ROUTE_KEY+"123",
               message, correlationData);
       TimeUnit.SECONDS.sleep(1);

       //消息持久化
        Message MessageProperties = MessageBuilder.withBody(message.getBytes(StandardCharsets.UTF_8))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        rabbitTemplate.convertAndSend(DIRECT_EXCHANGE,CommonConfig.DIRECT_ROUTE_KEY,message, correlationData);
    }

}

